package com.rgs.base.database;

import com.google.common.base.Strings;
import com.rgs.base.database.sql.ISqlFilter;
import com.rgs.base.database.sql.LikeTypeEnum;
import com.rgs.base.database.sql.SqlConditionEnum;
import com.rgs.base.database.sql.SqlFilterAnnotation;
import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.Field;
import java.util.Objects;

/**
 * @author Ren Gaoshuai
 * @ClassName MySqlUtil
 * @date 2022-01-24 15:32
 **/
@Slf4j
public class MySqlUtil {
    private static void sqlFilterJoinOne(Example.Criteria criteria,
                                         Object objValue, String columnName,
                                         LikeTypeEnum likeTypeEnum,
                                         SqlConditionEnum sqlConditionEnum) {}

    public <T1,T2 extends ISqlFilter> Example join(Class<T1> clazz, T2 filter){
        Example example = new Example(clazz);
        Example.Criteria criteria =example.createCriteria();
        //通过反射获取filter的属性
        Field[] fields = filter.getClass().getDeclaredFields();
        //遍历处理这些属性
        for (Field fieldTemp : fields) {
            //获取属性上的注解
            SqlFilterAnnotation annotation = fieldTemp.getAnnotation(SqlFilterAnnotation.class);
            if (Objects.isNull(annotation)){
                continue;
            }
            //关闭该属性安全检查，提升反射的速度
            fieldTemp.setAccessible(true);
            Object objValue = null;
            try{
                //获取该属性的类型
                objValue = fieldTemp.get(filter);
            }catch (IllegalAccessException exception) {
                log.error(exception.getMessage());
                continue;
            }
            if (Objects.isNull(objValue)){
                continue;
            }

            String columnName;
            LikeTypeEnum likeTypeEnum;

            columnName = annotation.columnName();
            likeTypeEnum = annotation.likeType();
            sqlFilterJoinOne(criteria, objValue, columnName, likeTypeEnum,
                    annotation.sqlCondition());
        }
        //拼接 排序字段
        if (!Strings.isNullOrEmpty(filter.getOrderByClause())){
            example.setOrderByClause(filter.getOrderByClause());
        }
        return example;
    }
}
